// 通用请求方法封装
import qs from 'qs'
import md5Libs from 'uview-ui/libs/function/md5'
import { JsonSort } from '@/utils/ksort'
const base64 = require('./base64.js').Base64
const host = process.env.VUE_APP_URL
const appid = 'baseline'

export default (url = '', data = {}, method = 'POST') => {
  let headers = {}
  let params = Object.assign(
    {
      timestamp: (new Date().getTime() / 1000).toFixed(0),
      mock: '0',
      appid,
    },
    data
  )
  // 加密签名sign
  let access_token = uni.getStorageSync('access_token')
  let member_id = uni.getStorageSync('member_id')
  // 获取 sign
  let str = ''
  for (let key in JsonSort(params)) {
    str += `${key}=${JsonSort(params)[key]}&`
  }
  let sort = `${str}key=${appid}`
  let sign = md5Libs.md5(sort)
  params.sign = sign
  // authentication
  let authentication = ''
  if (access_token && member_id) {
    authentication = 'USERID ' + base64.encode(`${appid}-${access_token}-${member_id}`)
  }

  if (method === 'POST') {
    headers = {
      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
      authentication: authentication || '',
    }
  } else if (method === 'GET') {
    headers = {
      Accept: 'application/json',
      'Content-Type': 'application/json;charset=utf-8',
      authentication: authentication || '',
    }
  }
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${host}${url}`,
      method,
      data: params,
      dataType: 'json',
      header: headers,
      success(res) {
        if (res.statusCode === 200) {
          let { code, data, message } = res.data
          if (code != 200 && code != 401 && code != 402 && message) {
            uni.showToast({
              icon: 'none',
              title: message,
            })
          }
          if (code == 401 || code == 402) {
            uni.reLaunch({
              url: '/pages/user/authorize',
            })
          }
          resolve(res.data)
        } else {
          uni.showToast({
            icon: 'none',
            title: `${url}接口500了~~~`,
          })
        }
      },
      fail(err) {
        uni.showToast({
          icon: 'none',
          title: `${url}接口500了~~~`,
        })
        reject(err)
      },
    })
  })
}
